<?php

namespace app\meizhuangapi\controller;
use app\agentapi\controller\Weixin as WeixinModel;
use think\Db;
use org\Redis;

use app\api\controller\User as UserCon;
/**
 * 用户管理
 * Class User
 * @package app\api
 */
class User extends UserCon
{
    /*
     * 微信小程序获取用户手机号
     */
    public function getUserMobile(){
        $token=input('post.token');
        $encryptedData = input('post.encryptedData');
        $iv = input('post.iv');
        $wxapp_id=input('post.wxapp_id');
        $redis = new Redis();
        $loginInfo=$redis->get($token);
        $weixinInfo=Db::name('wxapp')->where(['wxapp_id'=>$wxapp_id])->find();
        if(!$weixinInfo){
            return $this->renderError('未获取到小程序信息');
        }
        $appid =$weixinInfo['app_id'];
        $session_key =$loginInfo['session_key'];
        $openid=$loginInfo['openid'];
        $pc = new WeixinModel($appid, $session_key);
        $errCode=$pc->decryptData($encryptedData, $iv, $data);
        if ($errCode==0) {
            $numDatas = json_decode($data);
            $phone = $numDatas->phoneNumber;
            //更新用户手机号
            $userInfo = $this->getUser();
            Db::name('user')->where(['open_id'=>$openid])->update(['mobile'=>$phone]);
            Db::name('dealer_user')->where(['user_id'=>$userInfo['user_id']])->update(['mobile'=>$phone]);
            return $this->renderSuccess('更新手机号码成功');
        } else {
            return $this->renderError('更新手机号失败');
        }
    }
    /*
     * 微信公众号提现申请绑定手机号
     */
    public function addMobile(){
        $mobile=input('post.mobile');
        if(empty($mobile)){
            return $this->renderError('请输入手机号');
        }
        $chars = "/^((\(\d{2,3}\))|(\d{3}\-))?1(3|5|8|9)\d{9}$/";
        if (!preg_match($chars,$mobile)){
            return $this->renderError('手机号码格式不正确');
        }
        //判断该手机号是否已经绑定
        $info=Db::name('user')->where(['mobile'=>$mobile])->find();
        if($info){
            return $this->renderError('该手机号已占用，请重新输入');
        }
        $userInfo = $this->getUser();
        Db::name('user')->where(['user_id'=>$userInfo['user_id']])->update(['mobile'=>$mobile]);
        Db::name('dealer_user')->where(['user_id'=>$userInfo['user_id']])->update(['mobile'=>$mobile]);
        return $this->renderSuccess('手机号绑定成功');
    }
    /*
     * 修改自定义昵称
     */
    public function updateUsername(){
        $name=input('post.username');
        $userInfo = $this->getUser();
        $weixinInfo=Db::name('user')->where(['user_id'=>$userInfo['user_id']])->update(['username'=>$name]);
        if($weixinInfo){
            return $this->renderSuccess([],'修改成功');
        }
        return $this->renderError('修改失败');
    }

}
